﻿using System;
using System.Web.Mvc;
using DDDSample.Application.Book;
using DDDSample.Application.HandlingEvent;
using DDDSample.UI.Mvc.Models;

namespace DDDSample.UI.Mvc.Controllers
{
    public class TrackingController : Controller
    {
        private readonly IBookService _bookService;
        private readonly IHandlingEventService _handlingEventService;

        public TrackingController(IBookService bookService,IHandlingEventService handlingEventService)
        {
            _bookService = bookService;
            _handlingEventService = handlingEventService;
        }

        [HttpGet]
        [ActionName("Track")]
        public ActionResult TrackGet(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return View();
            }
            return Track(id);
        }

        [HttpPost]
        [ActionName("Track")]
        public ActionResult TrackPost(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                ViewData.ModelState.AddModelError("id", @"Id must by specified.");
                return View();
            }
            return Track(id);
        }

        private ActionResult Track(string id)
        {
            var cargoId = Guid.Parse(id);
            var cargo = _bookService.Find(cargoId);
            if (cargo == null)
            {
                ViewData.ModelState.AddModelError("id", @"Provided id is invalid.");
                return View();
            }
            var history = _handlingEventService.LookupHandlingHistoryOfCargo(cargoId);
            return View(new CargoTrackingViewModel(cargo, history));
        }
    }
}